<script setup lang="ts">
import {getCurrentInstance, reactive, ref} from "vue";
import {userAddAxios, type UserInfoAddReq} from "@/api/user_api";
import {Message} from "@arco-design/web-vue";
import {roleOptions} from "@/global/global";

const visible = ref(false);

const mitt = getCurrentInstance()

mitt?.proxy?.$Bus.on('openAddModal', () => {
  visible.value = true
})

const form = reactive<UserInfoAddReq & { re_password: string }>({
  user_name: "",
  nick_name: "",
  password: "",
  re_password: "",
  role: 1,
})

const formRef = ref()

function rePasswordValidator(value: string, callback: (error?: string) => void) {
  if (value !== form.password) {
    callback("密码不一致")
  }
}

async function addUser() {
  // val是undefined则表示校验通过
  let val = await formRef.value.validate()
  if (val) {
    return false
  }
  let rsp = await userAddAxios(form);
  if (rsp.code !== 0) {
    Message.error("添加失败")
    return false
  }
  Message.success("添加成功")
  close()
}

function close() {
  visible.value = false
  formReset()
}

function formReset() {
  formRef.value.resetFields(Object.keys(form))
  formRef.value.clearValidate(Object.keys(form))
}

</script>

<template>
  <a-modal title="添加用户" :visible="visible" :on-before-ok="addUser" @cancel="close">
    <a-form
        ref="formRef"
        :model="form">

      <a-form-item field="user_name" label="用户名" :rules="[{required:true,message:'请输入用户名'}]"
                   validate-trigger="blur">
        <a-input v-model="form.user_name" placeholder="用户名"></a-input>
      </a-form-item>

      <a-form-item field="nick_name" label="昵称" :rules="[{required:true,message:'请输入昵称'}]"
                   validate-trigger="blur">
        <a-input v-model="form.nick_name" placeholder="昵称"></a-input>
      </a-form-item>

      <a-form-item field="password" label="密码" :rules="[{required:true,message:'请输入密码'}]"
                   validate-trigger="blur">
        <a-input v-model="form.password" placeholder="密码"></a-input>
      </a-form-item>

      <a-form-item field="re_password" label="确认密码"
                   :rules="[{required:true,message:'请确认密码'},{validator:rePasswordValidator}]"
                   validate-trigger="blur">
        <a-input v-model="form.re_password" placeholder="确认密码"></a-input>
      </a-form-item>

      <a-form-item field="re_password" label="选择权限">
        <a-select v-model="form.role" :options="roleOptions" placeholder="选择权限"></a-select>
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<style scoped>

</style>
